<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="prevClickHandle(pageNo - 1)">
      上一页
    </button>
    <button
      v-if="startNumAndEndNum().start > 1"
      @click="prevClickHandle(1)"
      :class="{ active: pageNo === 1 }"
    >
      1
    </button>

    <button v-if="startNumAndEndNum().start > 2">···</button>

    <!-- 连续页码 -->
    <template v-for="(page, index) in startNumAndEndNum().end" :key="index">
      <button
        v-if="page >= startNumAndEndNum().start"
        @click="prevClickHandle(page)"
        :class="{ active: pageNo === page }"
      >
        {{ page }}
      </button>
    </template>

    <button v-if="startNumAndEndNum().end < totalPage - 1">···</button>
    <button
      v-if="startNumAndEndNum().end < totalPage"
      @click="prevClickHandle(totalPage)"
      :class="{ active: pageNo === totalPage }"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="totalPage === pageNo"
      @click="prevClickHandle(pageNo + 1)"
    >
      下一页
    </button>

    <!-- <button style="margin-left: 30px">共 {{ total }} 条</button> -->
  </div>
</template>

<script setup>
import { computed, defineProps, defineEmits } from 'vue'
const props = defineProps({
  pageNo: {
    type: Number
  },
  pageSize: {
    type: Number
  },
  total: {
    type: Number
  },
  continues: {
    type: Number
  }
})
/**
 * 总页数：向上取整
 */
const totalPage = computed(() => Math.ceil(props.total / props.pageSize))
/**
 * 连续页码
 * 当前页在中间
 * 假设连续页码数为5：取当前页的前后两个数字
 */
const startNumAndEndNum = () => {
  // 解构，避免每次都去写props.xxx
  const { pageNo, continues } = props
  // 初始化起止页码
  let start = 0
  let end = 0
  // 连续页码数大于总页码
  if (continues > totalPage.value) {
    start = 1
    end = totalPage.value
  } else {
    // 起始位置
    start = pageNo - parseInt(continues / 2)
    // 结束位置
    end = pageNo + parseInt(continues / 2)
    // 起始位置出现负数或0
    if (start < 1) {
      start = 1
      end = continues
    }
    // 结束位置超过总页码时
    if (end > totalPage.value) {
      end = totalPage.value
      start = totalPage.value - continues + 1
    }
  }
  return { start, end }
}
// 解构，简化在模板中的书写
/* const { start, end } = startNumAndEndNum()
console.log(start, end) */
/**
 * 向父组件传递所点击的内容
 */
const emit = defineEmits(['getPageNo'])
// 点击上一页
const prevClickHandle = (num) => {
  emit('getPageNo', num)
}
</script>
<style lang="scss" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
